using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using MongoDB;

namespace SkynetMongoDBAccess.Converter;

internal static class DocumentToEntityConverter
{
	public static GridFileEntity ConvertToGridFileEntity(this Document source)
	{
		GridFileEntity gridFileEntity = new GridFileEntity();
		if (source["_id"] != null)
		{
			gridFileEntity.id = source["_id"].ToString().Trim();
		}
		if (source["filename"] != null)
		{
			gridFileEntity.filename = source["filename"].ToString();
		}
		if (source["chunkSize"] != null)
		{
			gridFileEntity.chunkSize = source["chunkSize"].ToString();
		}
		if (source["contentType"] != null)
		{
			gridFileEntity.contentType = source["contentType"].ToString();
		}
		if (source["uploadDate"] != null)
		{
			gridFileEntity.uploadDate = DateTime.Parse(source["uploadDate"].ToString());
		}
		if (source["length"] != null)
		{
			gridFileEntity.length = source["length"].ToString();
		}
		if (source["md5"] != null)
		{
			gridFileEntity.md5 = source["md5"].ToString();
		}
		return gridFileEntity;
	}

	public static UserEntity ConvertToUserEntity(this Document source)
	{
		UserEntity userEntity = new UserEntity();
		if (source["user"] != null)
		{
			userEntity.User = source["user"].ToString().Trim();
		}
		if (source["pwd"] != null)
		{
			userEntity.Pwd = source["pwd"].ToString().Trim();
		}
		if (source["readOnly"] != null)
		{
			userEntity.IsReadOnly = bool.Parse(source["readOnly"].ToString().Trim());
		}
		return userEntity;
	}

	public static DataSet? ConvertToDataSet(this IEnumerable<Document> source)
	{
		DataSet? dataSet = new DataSet();
		DataTable dataTable = new DataTable();
		if (source.Count() > 0)
		{
			foreach (string key in source.First().Keys)
			{
				dataTable.Columns.Add(key);
			}
			foreach (Document item in source)
			{
				DataRow dataRow = dataTable.NewRow();
				foreach (DataColumn column in dataTable.Columns)
				{
					dataRow[column.ColumnName] = item[column.ColumnName];
				}
				dataTable.Rows.Add(dataRow);
			}
		}
		dataSet.Tables.Add(dataTable);
		return dataSet;
	}
}
